#include "DecryptWidget.h"
#include "Command.h"
#include "Controller.h"

using namespace kryptos::controller;

namespace kryptos { namespace ui {

DecryptWidget::DecryptWidget(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);

    ui.wBody->hide();
    ui.buttonBox->setEnabled(false);

    ui.labelError->hide();
    ui.lePassphrase->setProperty("wrong", false);

    connect(&Controller::instance(), SIGNAL(passphraseNeeded(std::string, std::string)), this, SLOT(slotAskForPassphrase(std::string, std::string)));
    connect(&Controller::instance(), SIGNAL(wrongPassphrase(std::string, std::string)) , this, SLOT(slotAskForPassphraseAgain(std::string, std::string)));
    connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(slotPassphraseReady()));
}

void DecryptWidget::setDecryptCommand(Command* cmd)
{
    Q_CHECK_PTR(cmd);
    m_decryptCmd = cmd;
}

void DecryptWidget::init()
{
    if (m_decryptCmd)
    {
        m_decryptCmd->execute();
    }
}

void DecryptWidget::slotAskForPassphrase(std::string name, std::string email)
{
    ui.lKey->setText(QString(std::string(name + " - " + email).c_str()));
    ui.wBody->show();
    ui.buttonBox->setEnabled(true);
}

void DecryptWidget::slotAskForPassphraseAgain(std::string name, std::string email)
{
    ui.lePassphrase->setProperty("wrong", true);
    ui.lePassphrase->style()->unpolish(ui.lePassphrase);
    ui.lePassphrase->style()->polish(ui.lePassphrase);
    ui.labelError->show();

    ui.lKey->setText(QString(std::string(name + " - " + email).c_str()));
    ui.wBody->show();
    ui.buttonBox->setEnabled(true);
}

void DecryptWidget::slotPassphraseReady()
{
    ui.labelError->hide();
    ui.lePassphrase->setProperty("wrong", false);
    ui.lePassphrase->style()->unpolish(ui.lePassphrase);
    ui.lePassphrase->style()->polish(ui.lePassphrase);

    Controller::instance().passphraseFromUserReady(ui.lePassphrase->text().toStdString());
}

}}
